package gdr.connection;

import gdr.battle.core.online.ServerManager;

import java.io.*;
import java.net.*;

/**
 * Realizzazione del server, si occupa di costruire il ServerThread del client sul server
 * @author Giorgio Vitale
 *
 */
public class Server implements Runnable{
	public static final int CONNESSIONE_IN_CORSO = 0;
	public static final int CONNESSO = 1;
	public static final int ARRESTATO = 2;
	protected int statoServer;
	
	protected ServerManager manager;
	protected Thread server;
	protected int port;
	protected volatile boolean stop;
	
	public Server(int port){
		this.port = port;
		statoServer = CONNESSIONE_IN_CORSO;
		manager = new ServerManager();
		server = new Thread(this);
		server.start();
		(new Thread(manager)).start();
	}
	
	public String getServerStateDescription(){
		switch (statoServer){
			case CONNESSIONE_IN_CORSO: return "Connessione in corso..";
			case CONNESSO: return "Connesso.";
			case ARRESTATO: return "Arrestato.";
			default: return "";
		}
	}
	
	public void stopServer(){
		stop = true;
		statoServer = ARRESTATO;
	}
	
	public void run(){
		try {
			ServerSocket socketConnection = new ServerSocket(port);
			statoServer = CONNESSO;
			while (!stop) {
				System.out.println("Server Waiting");
				Socket pipe = socketConnection.accept();
				ObjectInputStream serverInputStream = new ObjectInputStream(pipe.getInputStream());
				ObjectOutputStream serverOutputStream = new ObjectOutputStream(pipe.getOutputStream());
				
				ServerThread serverThread = new ServerThread(manager, pipe, serverInputStream, serverOutputStream);
				if (manager.addConnection(serverThread)) //se riesce ad aggiungerlo, lo avvia
					serverThread.start();
			} // end of the while loop
			socketConnection.close(); //chiude il socket
			socketConnection = null;
		}  catch(Exception e) {System.out.println(e); }
		
	}
	public static void create(String[] arg) {
		new Server(20000);
	}

	public ServerManager getManager() {
		return manager;
	}

	public void setManager(ServerManager manager) {
		this.manager = manager;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public int getStatoServer() {
		return statoServer;
	}
}